// 防抖函数
const debounce = (fn, delay, cacheKey='', immediate = true) => {
  // 1.定义一个定时器, 保存上一次的定时器
  
  let timer = JSON.parse(localStorage.getItem(cacheKey)) || null
  // window.console.log(fn, delay, timeout)
  // 2.真正执行的函数
  const _debounce = function() {
    let context = this
    let args = arguments
  
    if (timer) clearTimeout(timer) // timeout 不为null
    if (immediate) {
      // 第一次会立即执行，以后只有事件执行后才会再次触发
      let callNow = !timer
      timer = setTimeout(function() {
        timer = null
      }, delay)
      if (callNow) {
        fn.apply(context, args)
      }
    } else {
      timer = setTimeout(function() {
        fn.apply(context, args)
      }, delay)
    }
    localStorage.setItem(cacheKey, timer)
  }
  
  // 封装取消功能
  _debounce.cancel = function() {
    let timeout_cancel = JSON.parse(localStorage.getItem(cacheKey)) || null
    if (timeout_cancel) clearTimeout(timeout_cancel)
    //if (timer) clearTimeout(timer)
    timer = null
    localStorage.setItem(cacheKey, null)
  }
  
  return _debounce
}
  
export default debounce
  